package com.isunland.managesystem.ui;

import android.app.AlertDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.Button;
import butterknife.BindView;
import butterknife.ButterKnife;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.Base;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.SignSummaryOriginal;
import com.isunland.managesystem.utils.MyDateUtil;
import com.isunland.managesystem.utils.MyStringUtil;
import com.isunland.managesystem.utils.ParamsNotEmpty;
import com.isunland.managesystem.utils.ToastUtil;
import com.isunland.managesystem.widget.SingleLineView;
import java.util.ArrayList;
import java.util.Date;
import java.util.UUID;
import org.json.JSONException;

/**
 * 对象功能:
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: wangyanan
 * 创建时间: 2017/7/6 16:53
 */
public class BatchOverDialog extends BaseDialogFragment {
  @BindView(R.id.slv_startTime) SingleLineView slvStartTime;
  @BindView(R.id.slv_endTime) SingleLineView slvEndTime;
  @BindView(R.id.slv_mainContent) SingleLineView slvMainContent;
  @BindView(R.id.slv_subContent) SingleLineView slvSubContent;
  @BindView(R.id.btn_confirm) Button btnConfirm;
  /** 加班主表id */
  private String mMainId;
  /** 打卡记录,用于生成子表 */
  private ArrayList<SignSummaryOriginal.SignSummaryContent> mSignList;
  private int mCount;

  @Override public void initData() {
    super.initData();
    mMainId = UUID.randomUUID().toString();
  }

  @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) {
    super.onCreateDialog(savedInstanceState);
    AlertDialog.Builder builderSingle = new AlertDialog.Builder(getActivity());
    View v = mActivity.getLayoutInflater().inflate(R.layout.dialog_batch_over, null);
    ButterKnife.bind(this, v);
    btnConfirm.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        volleyPostGetSignList();
      }
    });
    return builderSingle.setView(v).create();
  }

  private void volleyPostGetSignList() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_ATTTENDANCE_LIST);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("curPage", "1");
    params.put("pageSize", "1000");
    params.put("type", "mobile");
    params.put("memberCode", CurrentUser.newInstance(mActivity).getMemberCode());
    params.put("arrJobNames", CurrentUser.newInstance(mActivity).getRealName());
    params.put("beginrecordDate",
        MyDateUtil.format(MyDateUtil.parse(slvStartTime.getTextContent(), "yyyyMMdd")));
    params.put("endrecordDate",
        MyDateUtil.format(MyDateUtil.parse(slvEndTime.getTextContent(), "yyyyMMdd")));
    mActivity.volleyPost(url, params.getParams(), new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {

      }

      @Override public void onVolleyResponse(String json) throws JSONException {
        SignSummaryOriginal original = new Gson().fromJson(json, SignSummaryOriginal.class);
        ArrayList<SignSummaryOriginal.SignSummaryContent> rows =
            (ArrayList<SignSummaryOriginal.SignSummaryContent>) original.getRows();
        if (rows == null || rows.size() == 0) return;
        mSignList = rows;
        volleypostMainOver();
      }
    });
  }

  private void volleypostMainOver() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_REQUISITION_SAVE_OR_RUN);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("id", mMainId);
    params.put("saveOrRun", "save");
    params.put("totalDesc", slvMainContent.getTextContent());
    params.put("attendType", "overnew");
    mActivity.volleyPost(url, params.getParams(), new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {

      }

      @Override public void onVolleyResponse(String json) throws JSONException {
        if (new Gson().fromJson(json, Base.class).getResult() != Base.SUCCESS) return;
        if (mSignList == null || mSignList.size() == 0) return;
        String startTime;
        String endTime;
        String hours;
        for (SignSummaryOriginal.SignSummaryContent item : mSignList) {
          //rsignInTime 应签到时间
          //rsignOutTime 应签退时间
          //psignInTime 实际签到时间
          //psignOutTime 实际签退时间 "2017-06-02 19:00:00",
          Date rsignInTime = MyDateUtil.parse(item.getRsignInTime());
          Date rsignOutTime = MyDateUtil.parse(item.getRsignOutTime());
          Date psignInTime = MyDateUtil.parse(item.getPsignInTime());
          Date psignOutTime = MyDateUtil.parse(item.getPsignOutTime());
          //非工作日加班
          if (rsignInTime == null
              && rsignOutTime == null
              && psignInTime != null
              && psignOutTime != null) {
            startTime = item.getPsignInTime();
            endTime = item.getPsignOutTime();
            hours = MyStringUtil.valueOf(
                (psignOutTime.getTime() - psignInTime.getTime()) / (60 * 60 * 1000.0));
            hours = MyStringUtil.substring(hours, 0, hours.indexOf(".") + 2);
            volleyPostChild(startTime, endTime, hours);
          }
          //工作日加班
          if (rsignInTime != null
              && rsignOutTime != null
              && psignInTime != null
              && psignOutTime != null
              && psignOutTime.after(rsignOutTime)
              && ((psignOutTime.getTime() - rsignOutTime.getTime()) > 60 * 60 * 1000)) {
            startTime = item.getRsignOutTime();
            endTime = item.getPsignOutTime();
            hours = MyStringUtil.valueOf(
                (psignOutTime.getTime() - rsignOutTime.getTime()) / (60 * 60 * 1000.0));
            hours = MyStringUtil.substring(hours, 0, hours.indexOf(".") + 2);
            volleyPostChild(startTime, endTime, hours);
          }
        }
      }
    });
  }

  private void volleyPostChild(String startTime, String endTime, String hours) {
    mCount++;
    if (MyStringUtil.isEmpty(startTime) || MyStringUtil.isEmpty(endTime)) return;
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_OVERSUB_SAVE);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("pid", mMainId);
    params.put("id", UUID.randomUUID().toString());
    params.put("overtimeReason", slvSubContent.getTextContent());
    params.put("actSTime", startTime);
    params.put("actETime", endTime);
    params.put("actWorkNum", hours);//加班工时,不能再循环里调用.
    mActivity.volleyPost(url, params.getParams(), new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {
        mCount--;
        if (mCount == 0) {
          ToastUtil.show("自动生成加班单完成,请到考勤填报中查看");
          dismiss();
        }
      }

      @Override public void onVolleyResponse(String json) throws JSONException {
        mCount--;
        if (mCount == 0) {
          ToastUtil.show("自动生成加班单完成,请到考勤填报中查看");
          dismiss();
        }
      }
    });
  }
}
